package com.cqhz.quwan.ui.main.fragment


import android.content.Intent
import android.support.v7.widget.StaggeredGridLayoutManager
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.LoginBean
import com.cqhz.quwan.model.PageResultBean
import com.cqhz.quwan.model.ProductBean
import com.cqhz.quwan.model.UserInfoBean
import com.cqhz.quwan.mvp.mall.MallContract
import com.cqhz.quwan.mvp.mall.MallPresenter
import com.cqhz.quwan.service.API
import com.cqhz.quwan.ui.base.AbsFragment
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.activity.MyExchangeActivity
import com.cqhz.quwan.ui.activity.ProductDetailActivity
import com.cqhz.quwan.ui.mine.DiamondRecordActivity
import com.cqhz.quwan.ui.widget.SameSpacesItemDecoration
import com.cqhz.quwan.util.CommonAdapterHelper
import com.cqhz.quwan.util.UmengAnalyticsHelper
import com.cqhz.quwan.util.formatMoney
import kotlinx.android.synthetic.main.fragment_mall.*
import me.militch.quickcore.core.HasDaggerInject
import me.militch.quickcore.mvp.model.ModelHelper
import javax.inject.Inject


/**
 * 首页-商城页面
 * Created by Guojing on 2018/10/18.
 */
class MallFragment : AbsFragment(), MallContract.View, HasDaggerInject<ActivityInject> {
    @Inject
    lateinit var modelHelper: ModelHelper
    @Inject
    lateinit var mallPresenter: MallPresenter
    var loginBean: LoginBean? = null
    private lateinit var productListAdapter: BaseQuickAdapter<*, *>
    private val products = ArrayList<ProductBean>()

    override fun inject(t: ActivityInject?) {
        t!!.inject(this)
    }

    companion object {
        fun newInstance() = MallFragment()
    }

    override fun layout(): Int {
        return R.layout.fragment_mall
    }

    override fun initView() {
        mallPresenter.attachView(this)
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo!!
            mallPresenter.getUserInfo(loginBean!!.userId!!)
        }

        // 获取和设置适配器
        productListAdapter = CommonAdapterHelper.getProductListAdapter(this!!.activity!!, products)
        rv_content.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        rv_content.adapter = productListAdapter
        val decoration = SameSpacesItemDecoration(1)
        rv_content.addItemDecoration(decoration)
        rv_content.setPadding(1, 1, 1, 1)
        rv_content.itemAnimator = null// 去除瀑布流会换列跳动
        rv_content.addOnItemTouchListener(object : OnItemClickListener() {
            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                val item = productListAdapter.getItem(position) as ProductBean
                if (loginBean == null) {
                    startActivity(Intent(context(), LoginActivity::class.java))
                } else {
                    val intent = Intent(context(), ProductDetailActivity::class.java)
                    intent.putExtra("productId", item.id)
                    startActivity(intent)
                }
            }
        })
        // 加载更多
        productListAdapter.setOnLoadMoreListener({
            if (products.size > 0) {
                if (products.size % KeyContract.pageSize == 0) {
                    val pageNo = products.size / KeyContract.pageSize + 1
                    refreshLayout.isEnableRefresh = false
                    mallPresenter.getProductList(pageNo, KeyContract.pageSize)
                } else {
                    productListAdapter.loadMoreEnd()
                }
            } else {
                refreshLayout.isEnableRefresh = false
                mallPresenter.getProductList(0, KeyContract.pageSize)
            }
        }, rv_content)
        // 刷新
        refreshLayout.setOnRefreshListener {
            mallPresenter.getProductList(1, KeyContract.pageSize)
        }
        // 加载数据
        mallPresenter.getProductList(1, KeyContract.pageSize)

        // 趣豆寻宝
        action_goto_web.setOnClickListener { gotoExchangeDiamonds() }
        // 我的领奖（我的兑换）
        action_goto_my_exchange.setOnClickListener { gotoActivity(MyExchangeActivity::class.java) }
        // 钻石记录
        action_goto_diamond_record.setOnClickListener { gotoActivity(DiamondRecordActivity::class.java) }
    }

    /**
     * 去抽钻
     */
    private fun gotoExchangeDiamonds() {
        val intent = Intent(context, if (loginBean == null) LoginActivity::class.java else WebViewActivity::class.java)
        if (loginBean != null) {
            intent.putExtra(KeyContract.Title, "趣豆寻宝")
            val url = "${API.findTreasure}?userId=${loginBean!!.userId}"
            intent.putExtra(KeyContract.Url, url)
        }
        startActivity(intent)
    }

    override fun showUserInfo(userInfoBean: UserInfoBean) {
        tv_diamonds.text = userInfoBean.diamonds.formatMoney()
    }

    override fun loadProductList(pageNo: Int, pageResultBean: PageResultBean<ProductBean>) {
        if (pageNo == 1) {
            products.clear()
            productListAdapter.setEnableLoadMore(true)
            if (refreshLayout?.state?.isHeader!!) {
                refreshLayout?.finishRefresh()
            }
        }

        if (pageResultBean.records.isNotEmpty()) {
            products.addAll(pageResultBean.records)
        }

        if (pageResultBean.total > products.size) {
            productListAdapter.loadMoreComplete()
        } else {
            productListAdapter.loadMoreEnd()
        }

        productListAdapter.notifyDataSetChanged()
        refreshLayout.isEnableRefresh = true
    }

    /**
     * 跳转到其他页面
     * @author Guojing
     */
    private fun gotoActivity(c: Class<*>) {
        startActivity(Intent(context, if (loginBean == null) LoginActivity::class.java else c))
    }

    override fun onResume() {
        super.onResume()
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo!!
            mallPresenter.getUserInfo(loginBean!!.userId!!)
        } else {
            tv_diamonds.text = "0"
        }
        UmengAnalyticsHelper.onPageStart("商城")// 统计页面
        UmengAnalyticsHelper.onResume(context())
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!isHidden) {
            this.onResume()
        } else {
            this.onPause()
        }
    }

    override fun onPause() {
        super.onPause()
        UmengAnalyticsHelper.onPageEnd("商城")// 统计页面
        UmengAnalyticsHelper.onPause(context())
    }

    override fun onDestroy() {
        super.onDestroy()
        mallPresenter.detachView()
    }
}
